var express = require('express')
var bodyparser = require('body-parser')

var cookieparser = require('cookie-parser')
var fs = require('fs')

var app = express()
app.use(express.static('www'))
app.use(bodyparser.urlencoded({ extended: false }))
app.use(cookieparser())
// 用户信息路径
var userfilepath = './users.json'
var questionpath = './question.json'
// 用户信息数组
var allusers;
if (fs.existsSync(userfilepath)) {
    var s = fs.readFileSync(userfilepath)
    allusers = JSON.parse(s)
}
else {
    allusers = []
}
//问题列表数组
var question;
if (fs.existsSync(questionpath)) {
    var s = fs.readFileSync(questionpath)
    question = JSON.parse(s)
}
else {
    question = []
}
// 注册接口
app.post('/user/regist', function (req, res) {
    var isuser = allusers.some(function (u) {
        return u.account == req.body.account
    })
    if (isuser) {
        res.json({ err: 1, msg: '用户名被占用' })
    }
    else {
        allusers.push(req.body)
        var s = JSON.stringify(allusers)
        fs.writeFileSync(userfilepath, s)
        res.json({ err: 0, msg: '注册成功' })
    }
})

// 登录接口
app.post('/user/login', function (req, res) {
    var user = allusers.find(function (u) {
        return u.account == req.body.account
    })
    if (!user) {
        res.json({ err: 1, msg: '用户名或密码错误' })
    }
    else {
        if (user.pwd == req.body.pwd) {
            res.cookie('token', user.account)
            res.json({ err: 1, msg: '登录成功' })
        }
        else {
            re.json({ err: 1, msg: '用户名或密码错误' })
        }
    }
})
// 问题接口
app.get ("/question/list",function(req,res){
        // var s =fs.readFileSync(questionpath)
        // var data = JSON.parse(s)
        // res.send(s)
        //  res.json({data:data})
        res.json({data:question})
})

//回答问题接口
app.post('/question/answer',function(req,res){
  var que =  question.find(function(q){
        return q.id == req.body.qid
    })
    if(!que){
        res.json({err:1,msg:'问题被删除'})
    }
    else{
        var ans = {
            txt:req.body.txt,
            ip:req.ip,
            date:new Date(),
            user:req.cookies.token
        }
        que.answers.push(ans)
        var s = JSON.stringify(question)
        fs.writeFileSync(questionpath,s)
        res.json({err:0,msg:'回答成功'})
    }
})

// 提问接口
app.post('/question/ask', function (req, res) {
    if (!req.cookies.token) {
        res.json({err: 1, msg: '未登录' })
    }
    else {
        var now = new Date()
        var q = {
            txt: req.body.txt,
            date: new Date(),
            user: req.cookies.token,
            ip: req.ip.substr(req.ip.lastIndexOf('.')),
            answers: [],
            id: now.getTime()
        }
        question.unshift(q)
        var s = JSON.stringify(question)
        fs.writeFileSync(questionpath, s)
        res.json({err: 0, msg: '问题提问成功' })

    }
})
app.listen(3000, function () {
    console.log('服务器跑起来了')
})